package com.wngbms.multidatasource.datasource.sharding.cipher;

import com.wngbms.multidatasource.datasource.sharding.ShardingTest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlEncryptDataSourceFactory;

import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
public class CipherDemo {

    public static void main(String[] args) throws IOException, SQLException {
        InputStream stream = ShardingTest.class.getResourceAsStream("/cipher/cipher.yml");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = stream.read(buf)) > 0) {
            outputStream.write(buf, 0, len);
        }

        DataSource dataSource = YamlEncryptDataSourceFactory.createDataSource(outputStream.toByteArray());

        Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();

        connection.setAutoCommit(false);
        boolean execute = statement.execute("insert into users (u_name, u_age, u_mobile ) values ('wngb', 15, '13321434152')");
        log.info("execute result:{}", execute);
        connection.commit();

        statement.close();
        connection.close();
    }

}
